#ifndef CONNECTION_H
#define CONNECTION_H

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include "RequestHandler.h"

namespace tsc
{
namespace common
{

/// Represents a single connection from a client.
class Connection
  : public boost::enable_shared_from_this<Connection>,
    private boost::noncopyable
{
public:
  /// Construct a connection with the given io_service.
  explicit Connection(boost::asio::io_service& service,
                      RequestHandler&          handler);

  /// Get the socket associated with the connection.
  boost::asio::ip::tcp::socket& socket();

  /// Start the first asynchronous operation for the connection.
  void start();

  void close();

private:
  /// Handle completion of a read operation.
  void handleRead(const boost::system::error_code& error,
                  std::size_t                      bytes_transferred);

  /// Handle completion of a write operation.
  void handleWrite(const boost::system::error_code& error);

  /// Socket for the connection.
  boost::asio::ip::tcp::socket mSocket;

  /// The handler used to process the incoming request.
  RequestHandler& mRequestHandler;

  /// Buffer for incoming data.
  boost::array<char, 8192> mBuffer;

  //! Connection description
  std::string mDescribeStr;

  //! Connection instance ID
  unsigned int mInstance;

  //! Connection instance counter
  static unsigned int sInstanceCounter;
};

typedef boost::shared_ptr<Connection> ConnectionP_t;

} // namespace common
} // namespace tsc

#endif // CONNECTION_H
